package user

import (
	//"fmt"
	"github.com/labstack/echo"
	"io/ioutil"
	. "model/api"
	"model/auth"
	. "model/constant"
	"net/http"
	"strconv"
	"strings"
)

type Credential struct {
	Uid   uint
	Token string
}

const (
	Token = "Token"
	Uid   = "Uid"
)

func RegisterHandlers(e *echo.Group) {

	// 本身登陆注销接口不需要这个中间件

	e.POST("/login", auth.Login)
	e.POST("/show_all", auth.ShowAll)
	e.POST("/show_rank", auth.ShowRank)
	e.POST("/vote", auth.Vote)

	e.POST("/user_auth", auth.UserAuth)

	//e.Use(AuthHandler)
	e.POST("/show", auth.Show)
}

func Login(c echo.Context) error {
	conn := db.Conn
	//user_name := c.QueryParam("user_name")
	u := new(User)
	if err := c.Bind(u); err != nil {
		panic(err.Error())
	}

	var user User
	rerr := conn.Where("name = ?", u.Name).First(&user)
	if rerr.RecordNotFound() == false {
		return c.JSON(http.StatusOK, Return{Status: STATUS_FAILURE, Reason: NAME_BEEN_REGISTERED})
	}

	rrerr := conn.Where("mobile = ?", u.Mobile).First(&user)
	if rrerr.RecordNotFound() == false {
		return c.JSON(http.StatusOK, Return{Status: STATUS_FAILURE, Reason: MOBILE_BEEN_REGISTERED})
	}

	token := CreateToken() //生成一个32位的token
	u.Token = token
	u.Modified = time.Now().Unix()
	u.Vote = 0

	err := conn.Create(&u).Error
	if err == nil {
		if u.ID > 0 {
			type result struct {
				ID    uint
				Token string
			}
			return c.JSON(http.StatusOK, Return{Status: STATUS_SUCCESS, Result: result{ID: u.ID, Token: u.Token}}) //代表注册成功
		}
	}

	return c.JSON(http.StatusOK, Return{Status: STATUS_FAILURE, Reason: REGISTER_FAIL})
}
